package com.jv.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jv.constant.SystemConstant;
import com.jv.entity.Admin;
import com.jv.entity.R;
import com.jv.service.IAdminService;
import com.jv.util.JwtUtils;
import com.jv.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author Jv
 * @version 1.0
 */
@RestController
public class AdminController {
    @Autowired
    private IAdminService adminService;

    /**
     * 管理员登录
     * @param admin
     * @return
     */
    @PostMapping("/adminLogin")
    public R adminLogin(@RequestBody Admin admin){
        if (admin == null) {
            return R.error();
        }
        if (StringUtil.isEmpty(admin.getUserName())) {
            return R.error("用户名不能为空！");
        }
        if (StringUtil.isEmpty(admin.getPassword())){
            return R.error("密码不能为空！");
        }
        //校验 先根据用户名查数据
        Admin resultAdmin = adminService.getOne(new QueryWrapper<Admin>().eq("userName", admin.getUserName()));
        if (resultAdmin == null) {
            return R.error("用户名不存在！");
        }//,再查密码
        if (!resultAdmin.getPassword().trim().equals(admin.getPassword())) {  //trim() 方法用于删除字符串的头尾空白符。
            return R.error("用户名或者密码错误！");
        }
        //身份正确 生成一个token
        String token = JwtUtils.createJWT("-1", "admin", SystemConstant.JWT_TTL);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        return R.ok(resultMap);
    }

    //修改密码
    @PostMapping("/admin/modifyPassword")
    public R modifyPassword(@RequestBody Admin admin){
        if (StringUtil.isEmpty(admin.getUserName())) {
            return R.error("用户名不能为空");
        }
        if (StringUtil.isEmpty(admin.getNewPassword())) {
            return R.error("新密码不能为空");
        }
        adminService.update(new UpdateWrapper<Admin>().set("password",admin.getNewPassword()).eq("userName",admin.getUserName()));
        return R.ok();
    }
}
